package com.jk.shiro;

import com.jk.entity.account.AccPermission;
import com.jk.entity.account.AccRole;
import com.jk.entity.account.AccUser;
import com.jk.service.account.AccUserService;
import com.jk.util.StringUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.List;

public class MyRealm extends AuthorizingRealm {

    @Autowired
    private AccUserService accUserService;

    /**
     * 为当前登录的Subject授予角色和权限
     */
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        String accUserId = principals.getPrimaryPrincipal().toString();
        List<String> roleList = new ArrayList<String>();
        List<String> permissionList = new ArrayList<String>();
        //从数据库中获取当前登录用户的详细信息
        try {
            List<AccRole> accRoleList = accUserService.getByUserId(accUserId);
            //实体类User中包含有用户角色的实体类信息
            if (null != accRoleList && accRoleList.size() > 0) {
                //获取当前登录用户的角色
                for (AccRole role : accRoleList) {
                    roleList.add(role.getAccRoleName());
                    //实体类Role中包含有角色权限的实体类信息
                    if (null != role.getPermissionList() && role.getPermissionList().size() > 0) {
                        //获取权限
                        for (AccPermission permission : role.getPermissionList()) {
                            if (!StringUtil.isEmpty(permission.getAccPermissionKey())) {
                                permissionList.add(permission.getAccPermissionKey());
                            }
                        }
                    }
                }
            } else {
                throw new AuthorizationException();
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new AuthorizationException();
        }

        //为当前用户设置角色和权限
        SimpleAuthorizationInfo simpleAuthorInfo = new SimpleAuthorizationInfo();
        simpleAuthorInfo.addRoles(roleList);
        simpleAuthorInfo.addStringPermissions(permissionList);
        return simpleAuthorInfo;
    }

    /**
     * 验证当前登录的Subject
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken) throws AuthenticationException {
        //获取基于用户名和密码的令牌  
        UsernamePasswordToken token = (UsernamePasswordToken) authcToken;
        AccUser accUser = accUserService.getByName(token.getUsername());
        if (null != accUser) {
            AuthenticationInfo authcInfo = new SimpleAuthenticationInfo(accUser.getAccUserId(), accUser.getAccUserPassword(), getName());
            this.setSession("currentUser", accUser);
            return authcInfo;
        } else {
            return null;
        }
    }

    /**
     * 将一些数据放到ShiroSession中,以便于其它地方使用
     */
    private void setSession(Object key, Object value) {
        Subject currentUser = SecurityUtils.getSubject();
        if (null != currentUser) {
            Session session = currentUser.getSession();
            System.out.println("Session默认超时时间为[" + session.getTimeout() + "]毫秒");
            if (null != session) {
                session.setAttribute(key, value);
            }
        }
    }
}